﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI.WebControls;
using Eassets.Service.Global;
using Eassets.Layered.Domain.Global;
using Eassets.Service.Asset;
using Eassets.Layered.Domain.Asset;
using System.Collections.ObjectModel;
using System.Text.RegularExpressions;

namespace Eassets.UI.Asset
{
    public partial class AssetsDisposalForm : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                GetOrganizationLevelList();
                GetAllMainCategory();
                //DataBindToFixedAssets();
                GetTransactionNumbers();
            }

        }

        protected void OrganizationLevelList_SelectedIndexChange(object sender, EventArgs e) 
        {
            GetTransactionNumbers();
        }

        private void GetTransactionNumbers()
        {
            TransactionService transactionService = new TransactionService();
            dropDownListTransactionNo.DataSource = transactionService.GetAllTransaction().Where(x=>x.TransactionDocumentCode=="DIS" && x.OrganizationLevelListId==Convert.ToInt64(dropDownListOrganizationLevelList.SelectedValue)).ToList();
            dropDownListTransactionNo.DataTextField = "TransactionNo";
            dropDownListTransactionNo.DataValueField = "TransactionId";
            dropDownListTransactionNo.DataBind();
        }

        private void GetOrganizationLevelList()
            {
            OrganizationLevelListService organizationLevelListService = new OrganizationLevelListService();
            List<OrganizationLevelList> organizationLevelLists = new List<OrganizationLevelList>();
            organizationLevelLists = organizationLevelListService.GetAllOrganizationLevelList().Where(x => x.OrganizationLevelMode == "B").ToList();
            dropDownListOrganizationLevelList.DataSource = organizationLevelLists;
            dropDownListOrganizationLevelList.DataValueField = "OrganizationLevelListId";
            dropDownListOrganizationLevelList.DataTextField = "Code";
            dropDownListOrganizationLevelList.DataBind();
        }

        private void GetAllMainCategory()
        {
            CategoryService categoryService = new CategoryService();
            Category category = new Category();
            try
            {
                dropDownListMainCategory.DataSource = categoryService.GetAllAssetCategory().Where(x => x.ParentId == 0).ToList();

                dropDownListMainCategory.DataValueField = "CategoryId";
                dropDownListMainCategory.DataTextField = "Description";
                dropDownListMainCategory.DataBind();

            }
            catch (Exception exception)
            {
                throw;
            }
        }

        protected void dropDownListMainCategory_SelectedIndexChanged(object sender, EventArgs e)
        {
            GetAllSubCategory();
        }

        protected void dropDownListSubCategory_SelectedIndexChanged(object sender, EventArgs e)
        {
            GetAssets();
        }

        protected void dropDownListAsset_SelectedIndexChanged(object sender, EventArgs e)
        {
            DataBindToGridView();
        }

        protected void DataBindToGridView()
        {
            List<AssetItemDetails> assetItemDetails = new List<AssetItemDetails>();
            assetItemDetails = GetFixedAssetItemDetailsByAssetId(Convert.ToInt64(dropDownListAsset.SelectedValue)).ToList();
            assetItemDetails = (from AssetItemDetail in assetItemDetails where AssetItemDetail.AssetStatus != "DIS" select AssetItemDetail).ToList();
            gridViewAssetDetails.DataSource = assetItemDetails;
            gridViewAssetDetails.DataBind();
        }

        //protected void gridViewAssetDetails_OnSelectedIndexChange(object sender,GridViewRowEventArgs e) 
        //{ 

        //}

        private void GetAssets()
        {
            AssetService assetService = new AssetService();
            Assets assets = new Assets();
            try
            {
                dropDownListAsset.DataSource = assetService.GetAllAsset().Where(x => x.AssetCategoryId == Convert.ToInt32(dropDownListlabelSubCategory.SelectedValue)).ToList();

                dropDownListAsset.DataValueField = "AssetId";
                dropDownListAsset.DataTextField = "Description";
                dropDownListAsset.DataBind();
            }
            catch (Exception exception)
            {
                throw;
            }
        }

        private void GetAllSubCategory()
        {
            CategoryService categoryService = new CategoryService();
            Category category = new Category();
            try
            {
                dropDownListlabelSubCategory.DataSource = categoryService.GetAllAssetCategory().Where(x => x.ParentId == Convert.ToInt32(dropDownListMainCategory.SelectedValue)).ToList();

                dropDownListlabelSubCategory.DataValueField = "CategoryId";
                dropDownListlabelSubCategory.DataTextField = "Description";
                dropDownListlabelSubCategory.DataBind();
            }
            catch (Exception exception)
            {
                throw;
            }
        }

        protected Collection<AssetItemDetails> GetFixedAssetItemDetailsByAssetId(long assetId)
        {
            Collection<AssetItemDetails> assetItemDetails = new Collection<AssetItemDetails>();
            AssetDisposalDetailsService assetDisposalDetailsService = new AssetDisposalDetailsService();
            assetItemDetails = assetDisposalDetailsService.GetFixedAssetItemDetailsByAssetId(assetId); ;
            return assetItemDetails;
        }

        

        //private void DataBindToFixedAssets()
        //{
        //    DataTable dataTable1 = new DataTable();
        //    dataTable1.Columns.Add("Asset");
        //    dataTable1.Columns.Add("Item Serial");
        //    dataTable1.Columns.Add("Pu. Date");
        //    dataTable1.Columns.Add("Pu. Value");
        //    dataTable1.Columns.Add("Cumulative Dep. Value");
        //    dataTable1.Columns.Add("Current Book Value");
        //    dataTable1.Columns.Add("Remaining Life Time");

        //    DataRow dataRow1 = dataTable1.NewRow();

        //    dataRow1["Asset"] = "Table000001";
        //    dataRow1["Item Serial"] = "000001";
        //    dataRow1["Pu. Date"] = "12/10/2010";
        //    dataRow1["Pu. Value"] = "100000";
        //    dataRow1["Cumulative Dep. Value"] = "25000";
        //    dataRow1["Current Book Value"] = "75000";
        //    dataRow1["Remaining Life Time"] = "48Months";

        //    try
        //    {
        //        dataTable1.Rows.Add(dataRow1);
        //        gridViewAssetDetails.DataSource = dataTable1;
        //        gridViewAssetDetails.DataBind();
        //    }

        //    catch (Exception ex)
        //    {

        //    }

        //}

        protected void buttonSave_OnClick(object sender, EventArgs e)
        {
            TransactionService transactionService = new TransactionService();
            AssetDisposalDetailsService assetDisposalDetailsService = new AssetDisposalDetailsService();
            Transaction transaction = new Transaction();
            transaction.TransactionTypeCode = Convert.ToString("ASDIS");
            transaction.TransactionDocumentCode = Convert.ToString("DIS");
            transaction.CompanyId = 0;
            transaction.OrganizationLevelListId = Convert.ToInt64(dropDownListOrganizationLevelList.SelectedValue);
            int serial = Getserial();
            //dropDownListTransactionNo.SelectedItem.Text = Convert.ToString(CreateNewTransactionCode((serial + 1)));

            //transaction.TransactionNo = "GAM/PRN/20120830/000001";
            //transaction.TransactionNo = (dropDownListTransactionNo.Text).Trim();
            transaction.TransactionNo = Convert.ToString(CreateNewTransactionCode((serial + 1)));
            transaction.TransactionUserId = 1;
            transaction.TransactionStatus = "A";
            //transaction.TransactionDate = DateTime.Now;

            AssetDisposalDetails assetDisposalDetails = new AssetDisposalDetails();
            transactionService.AddTransaction(transaction);

            long transactionId=transactionService.GetMaxTransactionNumber();


            //for (int i = 0; i < assetProcurementDetails.TransactionLine; i++)
            //{

            assetDisposalDetails.TransactionId = transactionId;


            assetDisposalDetails.AssetId = Convert.ToInt64(dropDownListAsset.SelectedValue);
            ViewState["AssetId"] = assetDisposalDetails.AssetId;
            assetDisposalDetails.AssetItemSerialCode = ViewState["SerialCode"].ToString();
            assetDisposalDetails.DisposalDate = Convert.ToDateTime(textBoxDisposalDate.Text);
            assetDisposalDetails.RemainingLifeTime = Convert.ToInt16(gridViewAssetDetails.SelectedRow.Cells[7].Text);
            assetDisposalDetails.SuggestedValue = Convert.ToDecimal(textBoxSuggestedValue.Text);
            assetDisposalDetails.Reason = textBoxReason.Text;
            assetDisposalDetailsService.AddFixedAssetDisposalDetails(assetDisposalDetails);

            OrganizationLevelListAssetService organizationLevelListAssetService = new OrganizationLevelListAssetService();
            organizationLevelListAssetService.MinusOrganizationLevelListAsset(Convert.ToInt64(ViewState["AssetId"]));


            //Get the SerialCode to be Disposal
           
            AssetItemDetailsService assetItemDetailsService = new AssetItemDetailsService();
            AssetItemDetails assetItemDetails = new AssetItemDetails();

            assetItemDetails = assetItemDetailsService.GetByIdAssetItemDetails(Convert.ToInt64(ViewState["AssetItemDetailsId"]));
            //assetItemDetails.AssetId=Convert.ToInt64(dropDownListAsset.SelectedValue);
            //assetItemDetails.AssetSerialCode=ViewState["SerialCode"].ToString();
            assetItemDetails.AssetStatus=Convert.ToString("DIS");
            assetItemDetailsService.ModifyAssetItemDetails(assetItemDetails);

            TransactionSerialService transactionSerialService = new TransactionSerialService();
            transactionSerialService.UpdateTransactionSerial("DIS");
            //}
        }

        private int Getserial()
        {
            long transactionSerial = 0;
            TransactionSerialService transactionSerialService = new TransactionSerialService();

            transactionSerial = transactionSerialService.GetMaxTransactionSerialByWorkFlowDocumentCode("DIS");
            return Convert.ToInt16(transactionSerial);
        }

        private String CreateNewTransactionCode(int maxSerial)
        {


            // int maxSerial = (Convert.ToInt16(transactionSerialDomain.Serial)+1);
            string maxSerialFormated;
            maxSerialFormated = CreateNumberFormat(Convert.ToInt16(maxSerial));
            Regex regex = new Regex("-");
            string locationCode = dropDownListOrganizationLevelList.SelectedItem.Text;
            string[] arrayParameters = regex.Split(locationCode);
            String yearMonth = DateTime.Now.ToString("yyyyMM");

            string OrganizationLevelListCode = Convert.ToString(arrayParameters[0]);

            string NewTransactionCode = (OrganizationLevelListCode + "/"
                                     + "DIS" + "/"
                                     + yearMonth + "/"
                                   + maxSerialFormated);
            return NewTransactionCode;
        }

        private String CreateNumberFormat(Int16 maxSerial)
        {
            string maxSerialCode;
            if ((maxSerial / 10) == 0)
            {
                maxSerialCode = "0000" + maxSerial;
            }
            else if ((maxSerial / 100) == 0)
            {
                maxSerialCode = "000" + maxSerial;
            }
            else if ((maxSerial / 1000) == 0)
            {
                maxSerialCode = "00" + maxSerial;
            }
            else if ((maxSerial / 10000) == 0)
            {
                maxSerialCode = "0" + maxSerial;
            }
            else
            {
                maxSerialCode = maxSerial.ToString();
            }
            return maxSerialCode;
        }

        protected void gridViewAssetDetails_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {

        }

        protected void gridViewAssetDetails_SelectedIndexChange(object sender, EventArgs e)
        {
            GridViewRow row = gridViewAssetDetails.SelectedRow;
            ViewState["AssetItemDetailsId"]=row.Cells[1].Text.Trim();
            ViewState["SerialCode"] = row.Cells[3].Text.Trim();

            textBoxSuggestedValue.Text = row.Cells[6].Text.Trim();

        }
    }
}